import { Key, useRef, useState } from 'react';
import { ActionType, BetaSchemaForm, ProFormInstance, ProTable } from '@ant-design/pro-components';
import { App, Button, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createUser, deleteUser, getUserList, updateUser } from '@/api/modules/user';
import { UserType } from '@/types/user';
import { userTableConfig } from '@/views/User/UserTableConfig';
import { isSuccessCode } from '@/utils/isSuccessCode';
import { getPageCount } from '@/utils/getPageCount';
import { userFormItem, userFormItemUpdate } from '@/views/User/UserFormItem';
import { modelOption, ModelOption } from '@/enums/modelOption';
import { useWitTheme } from '@/hook/useWitTheme';

export const User = () => {
  const { message, modal } = App.useApp();
  const actionRef = useRef<ActionType>();
  // 表单配置
  const [model, setModel] = useState(ModelOption.CREATE);
  const [id, setId] = useState<string | undefined>(undefined);
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const theme = useWitTheme();
  // 删除
  const onDelete = async (key: Key, record: UserType) => {
    if (record.userName === 'admin') {
      message.warning('此账号为系统内置账号不能删除！');
      actionRef.current?.reload();
      return;
    }
    try {
      await deleteUser({ params: { id: key } });
    } catch (e) {
      alert(e);
    }
    actionRef.current?.reload();
  };
  // 修改
  const onSave = async (values: UserType) => {
    try {
      await updateUser({ data: { ...values, id } });
    } catch (e) {
      alert(e);
    }
    setVisible(false);
    actionRef.current?.reload();
  };
  // 表格操作按钮
  const columnsOptions = (text: any, record: any, index: number, action: ActionType) => (
    <div>
      <Button
        type="link"
        key="editable"
        onClick={async () => {
          setVisible(true);
          await setModel(ModelOption.EDIT);
          formRef.current?.setFieldsValue(record);
          setId(record.id);
        }}
      >
        编 辑
      </Button>
      <Button
        type="link"
        onClick={async () => {
          setVisible(true);
          await setModel(ModelOption.VIEW);
          formRef.current?.setFieldsValue(record);
        }}
      >
        查 看
      </Button>
      <Popconfirm description="删除此行?" onConfirm={() => onDelete(record.id, record)} title="">
        <Button type="link" danger>
          删 除
        </Button>
      </Popconfirm>
    </div>
  );
  return (
    <div>
      <ProTable<UserType>
        {...userTableConfig}
        actionRef={actionRef}
        request={async (params, sort, filter) => {
          const c = params.current;
          delete params.current;
          params.pageNum = c;
          const { data, headers } = await getUserList({ params });
          return {
            data: data.data,
            success: isSuccessCode(data),
            total: getPageCount(headers),
          };
        }}
        tableRender={(props, defaultDom) => {
          props.columns?.map(item => {
            if (item.key === 'option') {
              // @ts-ignore
              item.render = columnsOptions;
            }
            return item;
          });
          return defaultDom;
        }}
        toolBarRender={() => {
          return [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                formRef.current?.resetFields();
                setVisible(true);
                setModel(ModelOption.CREATE);
              }}
              type="primary"
            >
              新建
            </Button>,
          ];
        }}
      />
      <BetaSchemaForm<UserType>
        formRef={formRef}
        open={visible}
        onOpenChange={setVisible}
        layoutType={theme.formType}
        title={modelOption[model]}
        resize={{
          maxWidth: window.innerWidth * 0.8,
          minWidth: 400,
        }}
        rowProps={{
          gutter: [16, 16],
        }}
        colProps={{
          span: 12,
        }}
        grid={theme.formType !== 'LightFilter' && theme.formType !== 'QueryFilter'}
        onFinish={async values => {
          if (ModelOption.CREATE === model) {
            modal.confirm({
              title: '提示',
              content: '是否确认该操作？',
              onOk: async () => {
                const { data } = await createUser({ data: values });
                if (isSuccessCode(data)) {
                  setVisible(false);
                  actionRef.current?.reload();
                }
              },
            });
          }
          if (ModelOption.EDIT === model) {
            // @ts-ignore
            delete values.userName;
            await onSave(values);
          }
        }}
        disabled={ModelOption.VIEW === model}
        columns={(ModelOption.CREATE === model ? userFormItem : userFormItemUpdate) as any}
      />
    </div>
  );
};

export default User;
